package com.springboot.controller.blogview;

import com.alibaba.fastjson.JSONObject;
import com.springboot.config.log.SpringBootRequestLog;
import com.springboot.config.controller.BaseController;
import com.springboot.config.error.MySpringBootException;
import com.springboot.jwt.dto.RequestComm;
import com.springboot.jwt.interfaces.JwtToken;
import com.springboot.returndata.dto.blog.ChangePassByEmailDto;
import com.springboot.returndata.dto.blog.UserEamilLoginDto;
import com.springboot.returndata.dto.blog.UserEamilRegisterDto;
import com.springboot.returndata.vo.blog.BlogCommentVo;
import com.springboot.service.blog.BlogCommentService;
import com.springboot.service.blog.BlogUserService;
import com.springboot.util.enums.RespErrorCode;
import com.springboot.util.http.MyHttpUtil;
import com.springboot.util.http.ResponseBuilder;
import com.springboot.util.http.ResultResponse;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @ClassName BlogUserController
 * @Description
 * @Author zyj
 * @Date 2023/5/17 16:15
 * @Version 1.0
 **/
@RestController
@RequestMapping("/blogViewController")
@Slf4j
@SpringBootRequestLog
@Tag(name = "博客页用户操作类")
@JwtToken(requestTokenType = RequestComm.REQUEST_TOKEN_TYPE_BLOGUSER, token=false)
public class BlogUserController extends BaseController {

    @Resource
    private BlogUserService blogUserService;

    @Resource
    private BlogCommentService blogCommentService;

    @Resource
    private MyHttpUtil myHttpUtil;

    @GetMapping("/sendEamilCode")
    @Operation(description = "用户注册发送邮箱验证码")
    public ResultResponse<String> sendEamilCode(@NotNull(message = "邮箱不能为空") @Email(message = "邮箱格式错误") String email) {
        try {
            String token = blogUserService.sendEamilCode(email);
            return ResponseBuilder.successData(token);
        } catch (MySpringBootException e) {
            return ResponseBuilder.errorMessage(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error("用户注册发送邮箱验证码 失败：", e);
            return ResponseBuilder.errorMessage(RespErrorCode.BLOG_EMAIL_ERROR.getValue(), RespErrorCode.BLOG_EMAIL_ERROR.getDescripe());
        }
    }


    @GetMapping("/sendEamilForgetCode")
    @Operation(description = "用户忘记密码发送邮箱验证码")
    public ResultResponse<String> sendEamilForgetCode(@NotNull(message = "邮箱不能为空") @Email(message = "邮箱格式错误") String email) {
        try {
            String token = blogUserService.sendEamilForgetCode(email);
            return ResponseBuilder.successData(token);
        } catch (MySpringBootException e) {
            return ResponseBuilder.errorMessage(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error("用户忘记密码发送邮箱验证码 失败：", e);
            return ResponseBuilder.errorMessage(RespErrorCode.BLOG_EMAIL_ERROR.getValue(), RespErrorCode.BLOG_EMAIL_ERROR.getDescripe());
        }
    }

    @PostMapping("/changePassByEmail")
    @Operation(description = "通过邮箱修改密码")
    public ResultResponse<String> changePassByEmail(@Validated @RequestBody ChangePassByEmailDto changePassByEmail) {
        try {
            blogUserService.changePassByEmail(changePassByEmail);
            return ResponseBuilder.success();
        } catch (MySpringBootException e) {
            return ResponseBuilder.errorMessage(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            log.error("通过邮箱修改密码 失败：", e);
            return ResponseBuilder.errorMessage(RespErrorCode.BLOG_EMAIL_ERROR.getValue(), RespErrorCode.BLOG_EMAIL_ERROR.getDescripe());
        }
    }


    @PostMapping("/userEamilRegister")
    @Operation(description = "博客用户注册")
    public ResultResponse<String> userEamilRegister(@Validated @RequestBody UserEamilRegisterDto userEamilRegisterDto) {
        try {
            blogUserService.userEamilRegister(userEamilRegisterDto);
            return ResponseBuilder.success();
        } catch (MySpringBootException me){
            return ResponseBuilder.errorMessage(me.getErrorCode(), me.getMessage());
        }catch (Exception e) {
            log.error("博客用户注册 失败：", e);
            return ResponseBuilder.errorMessage(RespErrorCode.BLOG_REGISTER_ERROR.getValue(), RespErrorCode.BLOG_REGISTER_ERROR.getDescripe());
        }
    }


    @PostMapping("/userEamilLogin")
    @Operation(description = "博客用户登录")
    public ResponseEntity<ResultResponse<Map<String, String>>> userEamilLogin(@Validated @RequestBody UserEamilLoginDto userEamilRegisterDto) {
        try {
            String host = getResponse().getHeader("Host");
            Map<String, String> jwt = blogUserService.userEamilLogin(userEamilRegisterDto);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            headers.set("Access-Control-Allow-Credentials", "true");
            headers.set("Access-Control-Allow-Origin", host);
            return ResponseBuilder.successHeaderData(jwt, headers);
        } catch (MySpringBootException me){
            return ResponseBuilder.errorHeaderMessage(me.getErrorCode(), me.getMessage());
        }catch (Exception e) {
            log.error("博客用户登录 失败：", e);
            return ResponseBuilder.errorHeaderMessage(RespErrorCode.BLOG_LOGIN_ERROR.getValue(), RespErrorCode.BLOG_LOGIN_ERROR.getDescripe());
        }
    }

    @GetMapping("/getCommentById")
    @Operation(description = "根据文章id获取评论")
    public ResultResponse<List<BlogCommentVo>> getCommentById(@RequestParam Integer articleId) {
        try {
            List<BlogCommentVo> commentById = blogCommentService.getCommentById(articleId);
            return ResponseBuilder.successData(commentById);
        } catch (Exception e) {
            log.error("根据文章id获取评论 失败：", e);
            return ResponseBuilder.errorMessage(RespErrorCode.BLOG_LOGIN_ERROR.getValue(), RespErrorCode.BLOG_LOGIN_ERROR.getDescripe());
        }
    }

    @GetMapping("/getUserIp")
    @Operation(description = "获取用户ip")
    public ResultResponse<JSONObject> getUserIp(@RequestParam(required = false) String ip) {
        try {
            return ResponseBuilder.successData(myHttpUtil.getIpJSON(ip));
        } catch (Exception e) {
            log.error("获取用户ip 失败：", e);
            return ResponseBuilder.errorMessage(RespErrorCode.BLOG_LOGIN_ERROR.getValue(), RespErrorCode.BLOG_LOGIN_ERROR.getDescripe());
        }
    }

}
